
-- 角色 starry
-- 装备 starry_hat
AddPrefabPostInit("starry",function(inst)
    ------------------------------------------------------主客函数
    inst.starry_nightvision = net_bool(inst.GUID, "starry_nightvision", "starry_nightvision_dirty")
    inst.starry_nightvision:set(false)
    local function UpdateVisionEffect(inst)
        if not inst.components.playervision then return end
        if inst.starry_nightvision:value() then
            inst.components.playervision:PushForcedNightVision(inst)
        else
            inst.components.playervision:PopForcedNightVision(inst)
        end
    end
    inst:ListenForEvent("starry_nightvision_dirty", UpdateVisionEffect)
    ------------------------------------------------------
    if not TheWorld.ismastershard then
        return
    end
    ------------------------------------------------------服务端函数
    local NIGHTVISIONMODULE_GRUEIMMUNITY_NAME = "wxnightvisioncircuit"
    local function ShouldEnableNightVision(inst)
        local inv = inst.components and inst.components.inventory
        if not TheWorld or inst:HasTag("playerghost") or TheWorld.state.isfullmoon or TheWorld.state.isday or TheWorld.state.isdusk then
            return false
        elseif inv and inv:EquipHasTag("starry_hat") and (TheWorld:HasTag("cave") or TheWorld.state.isnight) then
            return true
        end
        return false
    end
    local function UpdateNightVisionState(inst)
        local should_enable = ShouldEnableNightVision(inst)
        inst.starry_nightvision:set(should_enable)
        if should_enable then
            inst.components.grue:AddImmunity(NIGHTVISIONMODULE_GRUEIMMUNITY_NAME)
        else
            inst.components.grue:RemoveImmunity(NIGHTVISIONMODULE_GRUEIMMUNITY_NAME)
        end
    end
    local function on_un_equip(inst, data)
        local item = data and data.item or nil
        if item and item:IsValid() and item:HasTag("starry_hat") then
            UpdateNightVisionState(inst)
        end
    end
    ------------------------------------------------------
    inst:DoTaskInTime(0, function()
        inst:ListenForEvent("equip", on_un_equip)
        inst:ListenForEvent("unequip", on_un_equip)
        inst:ListenForEvent("ms_respawnedfromghost", UpdateNightVisionState)
        inst:ListenForEvent("ms_becameghost", UpdateNightVisionState)
        inst:WatchWorldState("isnight", UpdateNightVisionState, TheWorld)
        inst:WatchWorldState("isfullmoon", UpdateNightVisionState, TheWorld)
        inst:WatchWorldState("isday", UpdateNightVisionState, TheWorld)
        UpdateNightVisionState(inst)
    end)
end)
